package com.blog4j.article.component;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.blog4j.article.entity.ArticleEntity;
import com.blog4j.article.service.ArticleService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 98k灬
 * @version v1.0.0
 * @Description : 功能描述
 * @Create on : 2024/7/23 21:33
 **/
@Component
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class AsyncService {
    private final ArticleService articleService;

    /**
     * 当分类名称修改后，同步更新文章信息中的分类信息
     *
     * @param categoryId 分类ID
     * @param categoryName 分类名称
     */
    @Async
    public void updateArticleCategoryName(String categoryId, String categoryName) {
        LambdaQueryWrapper<ArticleEntity> wrapper = new LambdaQueryWrapper<ArticleEntity>()
                .eq(ArticleEntity::getCategoryId, categoryId);
        List<ArticleEntity> articleList = articleService.list(wrapper);
        if (CollectionUtil.isEmpty(articleList)) {
            return;
        }
        for (ArticleEntity article : articleList) {
            article.setCategoryName(categoryName);
        }
        articleService.updateBatchById(articleList);
    }

    /**
     * 当分类名称修改后，同步更新文章信息中的标签信息
     *
     * @param labelId 标签ID
     * @param labelName 标签名称
     */
    @Async
    public void updateArticleLabelName(String labelId, String labelName) {
        LambdaQueryWrapper<ArticleEntity> wrapper = new LambdaQueryWrapper<ArticleEntity>()
                .eq(ArticleEntity::getLabelId, labelId);
        List<ArticleEntity> articleList = articleService.list(wrapper);
        if (CollectionUtil.isEmpty(articleList)) {
            return;
        }
        for (ArticleEntity article : articleList) {
            article.setLabelName(labelName);
        }
        articleService.updateBatchById(articleList);
    }
}
